<template>
  <div class="checkout-container">
    <!-- 头部 -->
    <Header />
    
    <!-- 主体内容 -->
    <div class="main-content">
      <div class="checkout-wrapper">
        <h2 class="page-title">确认订单</h2>
        
        <!-- 收货地址 -->
        <div class="section-card">
          <div class="section-title">
            <i class="el-icon-location"></i>
            <span>收货地址</span>
          </div>
          
          <div class="address-content" v-if="!loading">
            <!-- 收货地址选择 -->
            <div class="address-list" v-if="addresses.length > 0">
              <div 
                v-for="address in addresses" 
                :key="address.id" 
                :class="['address-item', { 'active': selectedAddress && selectedAddress.id === address.id }]"
                @click="selectAddress(address)"
              >
                <div class="address-info">
                  <div class="address-header">
                    <span class="receiver">{{ address.receiver }}</span>
                    <span class="phone">{{ address.phone }}</span>
                    <span class="default-tag" v-if="address.isDefault === 1">默认</span>
                  </div>
                  <div class="address-detail">{{ address.province }}{{ address.city }}{{ address.district }}{{ address.detailAddress }}</div>
                </div>
                <div class="address-select" v-if="selectedAddress && selectedAddress.id === address.id">
                  <i class="el-icon-check"></i>
                </div>
              </div>
            </div>
            
            <!-- 无地址提示 -->
            <div class="no-address" v-else>
              <p>您还没有收货地址，请先添加</p>
            </div>
            
            <!-- 添加地址按钮 -->
            <div class="add-address">
              <el-button type="primary" size="small" @click="addAddress">添加新地址</el-button>
            </div>
          </div>
          
          <!-- 加载中 -->
          <div class="loading-wrapper" v-else>
            <el-skeleton :rows="3" animated />
          </div>
        </div>
        
        <!-- 订单信息 -->
        <div class="section-card">
          <div class="section-title">
            <i class="el-icon-shopping-cart-2"></i>
            <span>订单详情</span>
          </div>
          
          <!-- 商家订单列表 -->
          <div v-for="(group, merchantId) in groupedCart" :key="merchantId" class="merchant-order">
            <div class="merchant-info">
              <span class="merchant-name">{{ group.merchantName || '未知商家' }}</span>
            </div>
            
            <!-- 商品列表 -->
            <div class="order-items">
              <div v-for="item in group.items" :key="item.id" class="order-item">
                <div class="item-image">
                  <img :src="item.image || 'https://via.placeholder.com/60'" :alt="item.name">
                </div>
                <div class="item-info">
                  <div class="item-name">{{ item.name }}</div>
                  <div class="item-quantity">x{{ item.quantity }}</div>
                </div>
                <div class="item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              </div>
            </div>
            
            <!-- 备注输入 -->
            <div class="order-remark">
              <span class="remark-label">备注：</span>
              <el-input 
                v-model="remarkMap[merchantId]" 
                placeholder="请输入备注信息"
                size="small">
              </el-input>
            </div>
            
            <!-- 小计 -->
            <div class="order-subtotal">
              <span class="subtotal-label">小计：</span>
              <span class="subtotal-value">¥{{ calculateMerchantTotal(merchantId) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 支付方式 -->
        <div class="section-card">
          <div class="section-title">
            <i class="el-icon-wallet"></i>
            <span>支付方式</span>
          </div>
          
          <div class="payment-methods">
            <el-radio-group v-model="paymentMethod">
              <el-radio :label="1">微信支付</el-radio>
              <el-radio :label="2">支付宝</el-radio>
              <el-radio :label="3">校园卡</el-radio>
            </el-radio-group>
          </div>
        </div>
        
        <!-- 订单提交 -->
        <div class="checkout-footer">
          <div class="checkout-total">
            <div class="total-info">
              <span class="total-label">订单总计：</span>
              <span class="total-value">¥{{ calculateTotal() }}</span>
            </div>
            <div class="address-summary" v-if="selectedAddress">
              <span class="address-label">配送至：</span>
              <span class="address-value">{{ selectedAddress.province }}{{ selectedAddress.city }}{{ selectedAddress.district }}{{ selectedAddress.detailAddress }}</span>
            </div>
          </div>
          <div class="checkout-actions">
            <el-button @click="goBack">返回购物车</el-button>
            <el-button type="primary" @click="submitOrder" :loading="submitting">提交订单</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部 -->
    <Footer />
    
    <!-- 添加地址对话框 -->
    <el-dialog title="添加收货地址" :visible.sync="addressDialogVisible" width="500px">
      <el-form :model="addressForm" :rules="addressRules" ref="addressForm" label-width="100px">
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="addressForm.receiver" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input v-model="addressForm.province" placeholder="请输入省份"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="addressForm.city" placeholder="请输入城市"></el-input>
        </el-form-item>
        <el-form-item label="区/县" prop="district">
          <el-input v-model="addressForm.district" placeholder="请输入区/县"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input 
            type="textarea" 
            v-model="addressForm.detailAddress" 
            placeholder="请输入详细地址，如街道、门牌号等"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress" :loading="savingAddress">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Header from '@/components/Header'
import Footer from '@/components/Footer'
import { mapGetters, mapMutations } from 'vuex'
import { getUserAddresses, addAddress, setDefaultAddress } from '@/api/address'
import { createOrder, payOrder } from '@/api/order'
import { isValidPhone } from '@/utils'
import { getUserCartDetail, clearUserCart } from '@/api/cart'

export default {
  name: 'Checkout',
  components: {
    Header,
    Footer
  },
  data() {
    // 手机号码验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'))
      } else if (!isValidPhone(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    
    return {
      // 收货地址列表
      addresses: [],
      // 选中的地址
      selectedAddress: null,
      // 支付方式（1-微信支付，2-支付宝，3-校园卡）
      paymentMethod: 1,
      // 备注信息（按商家ID存储）
      remarkMap: {},
      // 加载状态
      loading: true,
      // 购物车数据
      cart: [],
      // 提交订单状态
      submitting: false,
      // 地址对话框显示状态
      addressDialogVisible: false,
      // 保存地址状态
      savingAddress: false,
      // 地址表单
      addressForm: {
        receiver: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      },
      // 地址表单验证规则
      addressRules: {
        receiver: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请输入省份', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请输入城市', trigger: 'blur' }
        ],
        district: [
          { required: true, message: '请输入区/县', trigger: 'blur' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 获取当前用户
    user() {
      return this.$store.state.user
    },
    // 按商家分组的购物车商品
    groupedCart() {
      const groups = {}
      
      this.cart.forEach(item => {
        const merchantId = item.merchantId
        
        if (!groups[merchantId]) {
          groups[merchantId] = {
            merchantName: item.merchantName,
            items: []
          }
          
          // 初始化备注
          if (!this.remarkMap[merchantId]) {
            this.$set(this.remarkMap, merchantId, '')
          }
        }
        
        groups[merchantId].items.push(item)
      })
      
      return groups
    }
  },
  created() {
    // 获取购物车数据
    this.fetchCartData()
    
    // 获取用户收货地址
    this.fetchAddresses()
  },
  methods: {
    ...mapMutations(['SET_CART']),
    // 获取购物车数据
    fetchCartData() {
      const userId = this.user.id
      getUserCartDetail(userId).then(response => {
        if (response.code == 200) {
          this.cart = response.data
          
          // 检查购物车是否为空
          if (this.cart.length === 0) {
            this.$message.warning('购物车为空，请先添加商品')
            this.$router.push('/cart')
            return
          }
          
          // 同步到Vuex
          this.SET_CART(response.data)
        } else {
          this.$message.error(response.message || '获取购物车失败')
          this.$router.push('/cart')
        }
      }).catch(error => {
        console.error('获取购物车失败', error)
        this.$message.error('获取购物车失败，请稍后再试')
        this.$router.push('/cart')
      })
    },
    // 获取用户收货地址
    fetchAddresses() {
      this.loading = true
      
      getUserAddresses(this.user.id).then(response => {
        if (response.code === 200) {
          this.addresses = response.data
          if(!this.addresses){
           this.$message.warning('您还没有收货地址，请先添加')
           this.$router.push('/address')
           return
          }
          
          // 设置默认选中地址
          const defaultAddress = this.addresses.find(addr => addr.isDefault)
          this.selectedAddress = defaultAddress || (this.addresses.length > 0 ? this.addresses[0] : null)
        } else {
          this.$message.error(response.data.message || '获取收货地址失败')
        }
      }).catch(error => {
        console.error('获取收货地址失败', error)
        this.$message.error('获取收货地址失败，请稍后再试')
      }).finally(() => {
        this.loading = false
      })
    },
    // 选择收货地址
    selectAddress(address) {
      this.selectedAddress = address
    },
    // 显示添加地址对话框
    addAddress() {
      this.addressForm = {
        receiver: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      }
      this.addressDialogVisible = true
    },
    // 保存收货地址
    saveAddress() {
      this.$refs.addressForm.validate(valid => {
        if (valid) {
          this.savingAddress = true
          
          // 构建地址数据
          const addressData = {
            userId: this.user.id,
            receiver: this.addressForm.receiver,
            phone: this.addressForm.phone,
            province: this.addressForm.province,
            city: this.addressForm.city,
            district: this.addressForm.district,
            detailAddress: this.addressForm.detailAddress,
            isDefault: this.addressForm.isDefault ? 1 : 0 // 转换为后端需要的数字格式
          }
          
          // 调用添加地址API
          addAddress(addressData)
            .then(response => {
              if (response.code === 200) {
                // 添加成功
                this.$message.success('添加地址成功')
                this.addressDialogVisible = false
                
                // 刷新地址列表
                this.fetchAddresses()
              } else {
                this.$message.error(response.message || '添加地址失败')
              }
            })
            .catch(error => {
              console.error('添加地址失败', error)
              this.$message.error('添加地址失败，请稍后再试')
            })
            .finally(() => {
              this.savingAddress = false
            })
        }
      })
    },
    // 计算指定商家的商品总价
    calculateMerchantTotal(merchantId) {
      const group = this.groupedCart[merchantId]
      if (!group) return 0
      
      return group.items.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0).toFixed(2)
    },
    // 计算所有商品的总价
    calculateTotal() {
      return this.cart.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0).toFixed(2)
    },
    // 返回购物车
    goBack() {
      this.$router.push('/cart')
    },
    // 提交订单
    submitOrder() {
      // 验证收货地址
      if (!this.selectedAddress) {
        this.$message.warning('请选择收货地址')
        return
      }
      
      // 验证支付方式
      if (!this.paymentMethod) {
        this.$message.warning('请选择支付方式')
        return
      }
      
      this.submitting = true
      
      // 对于每个商家创建一个订单和订单项
      const createOrderPromises = Object.keys(this.groupedCart).map(merchantId => {
        const group = this.groupedCart[merchantId]
        
        // 计算订单总价
        const totalPrice = this.calculateMerchantTotal(merchantId)
        
        // 创建订单对象
        const orderData = {
          userId: this.user.id,
          merchantId: Number(merchantId),
          addressId: this.selectedAddress.id,
          paymentMethod: this.paymentMethod,
          remark: this.remarkMap[merchantId] || '',
          totalPrice: totalPrice, // 添加订单总价
          // 添加订单项数组 - 确保字段名称与后端 OrderDetail 实体一致
          items: group.items.map(item => ({
            foodId: item.foodId,
            foodName: item.name,
            foodImage: item.image,
            price: item.price,
            quantity: item.quantity,
            subtotal: item.price * item.quantity
          }))
        }
        
        console.log('创建订单数据:', JSON.stringify(orderData))
        
        // 提交订单
        return createOrder(orderData)
      })
      
      // 使用Promise.all处理所有订单创建请求
      Promise.all(createOrderPromises)
        .then(responses => {
          const hasError = responses.some(res => res.code !== 200)
          
          if (!hasError) {
            this.$message.success('订单创建成功，即将跳转到支付页面')
            
            // 获取第一个订单ID (示例中简化处理，实际可能需要展示多个订单)
            const firstOrderId = responses[0].data.id
            
            // 清空购物车
            this.clearCartAndRedirect(firstOrderId)
          } else {
            // 有订单创建失败
            const errorMsg = responses.find(res => res.code !== 200)?.message || '部分订单创建失败'
            this.$message.error(errorMsg)
            this.submitting = false
          }
        })
        .catch(error => {
          console.error('提交订单失败', error)
          this.$message.error('提交订单失败，请稍后再试')
          this.submitting = false
        })
    },
    
    // 清空购物车并跳转
    clearCartAndRedirect(orderId) {
      // 清空购物车（调用后端API）
      const userId = this.user.id
      clearUserCart(userId)
        .then(() => {
          // 清空本地购物车状态
          this.SET_CART([])
          
          // 跳转到订单列表页
          this.$router.push('/orders')
        })
        .catch(error => {
          console.error('清空购物车失败', error)
          // 即使清空购物车失败，也继续跳转
          this.$router.push('/orders')
        })
        .finally(() => {
          this.submitting = false
        })
    }
  }
}
</script>

<style scoped>
.checkout-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.main-content {
  flex: 1;
  padding: 30px 0;
}

.checkout-wrapper {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.section-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.section-title i {
  margin-right: 10px;
  color: #409EFF;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.address-item {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #c0c4cc;
}

.address-item.active {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.address-header {
  margin-bottom: 10px;
}

.receiver {
  font-weight: bold;
  margin-right: 10px;
}

.phone {
  color: #606266;
}

.default-tag {
  background-color: #f56c6c;
  color: #fff;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 2px;
  margin-left: 10px;
}

.address-detail {
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.address-select {
  position: absolute;
  right: 15px;
  bottom: 15px;
  color: #409EFF;
}

.no-address {
  text-align: center;
  padding: 20px 0;
  color: #909399;
}

.add-address {
  text-align: center;
}

.loading-wrapper {
  padding: 20px 0;
}

.merchant-order {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 20px;
}

.merchant-order:last-child {
  margin-bottom: 0;
}

.merchant-info {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.order-items {
  margin-bottom: 15px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px dashed #ebeef5;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 15px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.item-quantity {
  color: #909399;
  font-size: 14px;
}

.item-price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.order-remark {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.remark-label {
  width: 50px;
  flex-shrink: 0;
}

.order-subtotal {
  text-align: right;
  font-size: 16px;
}

.subtotal-value {
  color: #f56c6c;
  font-weight: bold;
}

.payment-methods {
  padding: 10px;
}

.checkout-footer {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.total-info {
  margin-bottom: 10px;
}

.total-value {
  color: #f56c6c;
  font-weight: bold;
  font-size: 22px;
}

.address-summary {
  font-size: 14px;
  color: #606266;
}

.address-value {
  max-width: 300px;
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}
</style> 